package com.boomsecret.lock;

import org.apache.commons.lang3.RandomUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

/**
 * Created by wangjinliang on 2018/8/8.
 */
public class CacheLockDemo {

    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    private static List<String> list = new ArrayList<String>();

    public static void main(String[] args) throws Exception {
        new Thread(() -> {
            while (true) {
                printCacheData();
                try {
                    Thread.sleep(800);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        Thread.sleep(3000);
        new Thread(() -> {
            while (true) {
                updateCacheData();
                try {
                    Thread.sleep(2033);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private static void updateCacheData() {
        WriteLock writeLock = lock.writeLock();
        writeLock.lock();
        list.clear();
        writeLock.unlock();
    }

    public static void printCacheData() {
        ReadLock readLock = lock.readLock();
        readLock.lock();
        if (list.size() == 0) {
            readLock.unlock();
            WriteLock writeLock = lock.writeLock();
            writeLock.lock();
            if (list.size() == 0) {
                list.clear();
                int updateCacheData = RandomUtils.nextInt();
                list.add("NewData -> " + updateCacheData);
                System.out.println("update cache data " + updateCacheData);
            }
            writeLock.unlock();
            readLock = lock.readLock();
            readLock.lock();
        }
        readLock.unlock();
        System.out.println("obtain cache data " + list.get(0));
    }
}

